<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        #box {
            width: 300px;
            height: 300px;
            border: 1px dashed red;
        }
    </style>
</head>

<body>
    <a href="/news">news</a>
    <a href="/messages">messages</a>
    <hr>
    <div id="box"></div>
    <script>
        //获取div元素
        let box = document.querySelector('#box');
        //获取a标签
        let a = document.querySelectorAll('a'); //NodeList(2) [a, a]
        //循环添加事件
        a.forEach(item => {
            item.onclick = function (e) {
                //阻止事件的默认行为
                e.preventDefault();
                //如何获取到/news或者是/messages
                // console.dir(e.target.href)
                //在历史记录中添加新状态
                history.pushState({}, '', e.target.href);
                //从地址对象中获取出来的pathname地址名称
                let { pathname } = location
                //判断
                switch (pathname) {
                    case '/news':
                        box.innerHTML = '我是news组件的内容';
                        break;
                    case '/messages':
                        box.innerHTML = '我是messaages组件的内容';
                        break;
                }
            }
        })
    </script>
</body>

</html>